package com.greatchn.authorization_server.config;

import com.greatchn.authorization_server.constant.Constant;
import com.greatchn.authorization_server.handler.AccessTokenConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @CustomAuthorizationServerConfig: 授权服务 config
 * @author: ZBoHang
 * @time: 2023/2/27 13:29
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    private DataSource dataSource;
    @Resource
    private AccessTokenConverter accessTokenConverter;

    /**
     * 配置安全约束
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 放开 /oauth/check 端点 供资源服务器校验token的合法性
        security.passwordEncoder(NoOpPasswordEncoder.getInstance())
                .checkTokenAccess("permitAll()")
                .tokenKeyAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }

    /**
     * 配置客户端
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(jdbcClientDetailsService()).build();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                // 配置token的管理
                .tokenServices(tokenServices())
                .accessTokenConverter(jwtAccessTokenConverter())
                // 默认POST 指定GET方便测试
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

    /**
     * 配置令牌管理服务
     * @return
     */
    @Bean
    public AuthorizationServerTokenServices tokenServices() {

        DefaultTokenServices services = new DefaultTokenServices();
        // 配置客户端详情服务，获取客户端的信息
        services.setClientDetailsService(new JdbcClientDetailsService(this.dataSource));
        // 支持刷新令牌
        services.setSupportRefreshToken(true);
        // 配置令牌的存储方式，此时采用内存方式存储
        services.setTokenStore(tokenStore());
        // 访问令牌有效时间2小时
        services.setAccessTokenValiditySeconds(7200);
        // 刷新令牌的有效时间3天
        services.setRefreshTokenValiditySeconds(259200);
        // JWT token 增强 ##(JWT token 时配置)
        services.setTokenEnhancer(jwtAccessTokenConverter());

        return services;
    }

    /**
     * 令牌管理
     */
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * JWT 令牌存储转化
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {

        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(Constant.JWT_SECRET_KEY);
        // 设置token转化
        jwtAccessTokenConverter.setAccessTokenConverter(this.accessTokenConverter);

        return jwtAccessTokenConverter;
    }

    /**
     * 客户端信息
     */
    @Bean
    public JdbcClientDetailsService jdbcClientDetailsService() {
        return new JdbcClientDetailsService(this.dataSource);
    }
}
